import _ from 'lodash'
import {Message, Loading} from 'element-ui'
import axios from 'axios';
import utils from './utils'
import config from '../config/config'

let base = config.PARAM.API_BASE_URL;
let apiName = config.apiName;

let message = {
  success: function (msg) {
    Message.closeAll();
    Message({
      type: 'success',
      iconClass: 'none',
      customClass: 'lj-message-success',
      dangerouslyUseHTMLString: true,
      message: '<div class="lj-message-box"><span class="lj-message-icon"><i class="iconfont icon-chenggong"></i></span><span class="lj-message-text">' + msg + '</span></div>'
    })
  },
  error: function (msg) {
    Message.closeAll();
    Message({
      type: 'error',
      iconClass: 'none',
      customClass: 'lj-message-error',
      dangerouslyUseHTMLString: true,
      message: '<div class="lj-message-box"><span class="lj-message-icon"><i class="iconfont icon-shibai"></i></span><span class="lj-message-text">' + msg + '</span></div>'
    });
  }
};


let loading = function () {
  config.screen_page_loading = Loading.service({
    lock: true,
    text: 'Loading',
    spinner: 'el-icon-loading',
    background: 'rgba(0, 0, 0, 0.7)',
    fullscreen: true
  });
};
let closeLoading = function () {
  var $screen = document.querySelector('.is-fullscreen');
  if (config.screen_page_loading) {
    config.screen_page_loading.close();
  } else {
    if ($screen)
      $screen.remove();
  }
};

let user = {
  set(data) {
    utils.setCookie(config.cookieName.user, data, 7 * 24 * 60);
  },
  get() {
    return utils.getCookie(config.cookieName.user) || {};
  },
  remove() {
    utils.removeCookie(config.cookieName.user);
  },
  getToken() {
    return this.get().token;
  },
  getMobile() {
    return this.get().mobile;
  },
  getUserName() {
    return this.get().mobile;
  },
  getRole() {
    return this.get().role;
  }
};

function ajax(api, params) {
  let _api = api.indexOf('://') > -1 ? api : (base + api);
  let token = user.getToken();
  if (!token && window.location.href.indexOf('login') == -1) goLogin();
  if (!!token) axios.defaults.headers['token'] = token;
  //console.log('api ------- send',_api,params,token,utils.getCookie(config.cookieName.user))
  params = params || {};
  return axios.post(_api, params).then((res) => {
    switch (res.data.code) {
      case 501:// 未登录
        goLogin();
        return {};
        break;
      case 513:
        message.error(res.data.msg || '程序异常，工程师正在修复……');
        return {};
      case 0:
        return res.data || {};
      default:
        var msg;
        if (config.ENV.toLowerCase() == 'prod') {
          if (res.data.code == 500) {
            msg = '账户名或密码错误,请重试';
          } else {
            msg = res.data.msg || '程序异常，工程师正在修复……';
          }
        } else {
          msg = '接口：' + api + ',异常信息：' + (res.data.msg || 'FE友情提示，未知错误');
        }
        message.error(msg);
        return res.data || {};
    }
  }).catch(ex => {
    try {
      message.error('网络异常，或者接口请求异常。接口：' + api);
    } catch (e) {
      alert('网络异常，或者接口请求异常。接口：' + api);
    }
  });
}

function goLogin() {
  window.location.href = '/view/login';
}

function goRouter(scope, routerName, params, isQuery) {
  let path;
  if (!!isQuery) { // routerName:/params?queryName=queryValue
    if (!!params) {
      scope.$router.push({path: routerName, query: params})
    } else {
      scope.$router.push({path: routerName});
    }
  } else {
    path = (!!params && params.length > 0) ? '/' + routerName + '/' + params.join('/') : '/' + routerName;
    scope.$router.push({path: path});
  }
}

var url = {
  go: function (scope, routerName, params, isQuery) {
    let path;
    if (!!isQuery) { // routerName:/params?queryName=queryValue
      if (!!params) {
        scope.$router.push({path: routerName, query: params})
      } else {
        scope.$router.push({path: routerName});
      }
    } else {
      path = (!!params && params.length > 0) ? '/' + routerName + '/' + params.join('/') : '/' + routerName;
      scope.$router.push({path: path});
    }
  },
  back: function (scope) {
    scope.$router.go(-1);
  },
  open: function (path) {
    var url = '';
    if (path.indexOf('http') > -1 && path.indexOf('://') > -1) {
      url = path;
    } else {
      url = window.location.href.split('#')[0] + '#/' + path;
    }
    url = url.replace('#//', '#/');
    $('body').append($('<a href="' + url + '" target="_blank" id="__openNewWindow"></a>'));
    document.getElementById("__openNewWindow").click();
    $('#__openNewWindow').remove();
  },
  close: function () {
    window.close();
  },
  genParams: function (data) {
    if (typeof data != 'object') {
      return '';
    }
    var result = '';
    for (var key in data) {
      result += key + '=' + data[key] + '&';
    }
    return result.slice(0, result.length - 1);
  },
  parseParams: function (key) {
    var paramStr = window.location.search.substring(1);
    var result = null;
    var params, paramArr;
    if (paramStr.length > 0) {
      params = paramStr.split("&");
      if (typeof key == 'undefined') {
        result = {};
        for (var i = 0; i < params.length; i++) {
          paramArr = params[i].split("=");
          result[paramArr[0]] = paramArr[1];
        }
        if ($.isEmptyObject(result)) {
          result = null;
        }
      } else {
        for (var j = 0; j < params.length; j++) {
          paramArr = params[j].split("=");
          var indexKey = paramArr[0];
          if (key == indexKey) {
            result = paramArr[1];
          }
        }
      }
    }
    return result;
  }
};

function routerBack(scope) {
  scope.$router.go(-1);
}

function parseEditorJSON(data) { // 解析编辑器的json数据
  if (!data) return data;

  // todo 这里要解决早期编辑器的乱码问题
  function removeHTMLTag(str) {
    str = str.replace(/<\/?[^>]*>/g, ''); //去除HTML tag
    str = str.replace(/[ | ]*\n/g, '\n'); //去除行尾空白
    //str = str.replace(/\n[\s| | ]*\r/g,'\n'); //去除多余空行
    //str = str.replace(/ /ig, '');//去掉
    str = str.replace(/&nbsp;/g, '');
    return str;
  }

  //console.log(removeHTMLTag(data));
  return typeof data == 'object' ? data : JSON.parse(data);
}

function compare(origin, target) {
  if (typeof target === 'object' && target != null) {
    if (typeof origin !== 'object') return false;
    for (let key of Object.keys(target))
      if (!compare(origin[key], target[key])) return false;
    return true
  } else return origin == target;
}

function passCheck(value) {
  if (value == undefined) {
    return false;
  } else if (value == 'undefined') {
    return false;
  } else if (value == null) {
    return false;
  } else if (value == 'null') {
    return false;
  } else if (_.trim(value) == '') {
    return false;
  } else if (_.isNaN(value)) {
    return false;
  }
  return true;
}

// 组合查询条件
function genQueryTerms(terms) {
  // 必须是map，且不能是空map
  let result = '';
  if (!_.isEmpty(terms)) {
    for (let key in terms) {
      let _value = terms[key];
      result += (key + '=' + (typeof _value == 'object' ?
        JSON.stringify(_value) : _value) + '&');
    }
    result = result.indexOf('&') > -1 ? result.substring(0, result.length - 1) : result;
  }
  return encodeURIComponent(result);
}

// 解析查询参数
function parseQueryTerms(termsStr) {
  if (!termsStr) return {};
  termsStr = decodeURIComponent(termsStr);
  var result = {};
  var params, item;
  if (termsStr.length > 0) {
    params = termsStr.split("&");
    for (let i = 0; i < params.length; i++) {
      item = params[i].split("=");
      result[item[0]] = item[1];
    }
  }
  return result;
}

function setTitle(title) {
  document.getElementsByTagName('title')[0].innerHTML = title;
}

function upload(file, api, callbackFn) {
  var uploadApi = api.indexOf('://') > -1 ? api : (base + api); /// url地址
  var uploadSuccessIndex = 0;
  var fileUrls = [];
  self.loading_remark = true;
  for (var i = 0, len = file.length; i < len; i++) {
    var $file = file[i];
    var formData = new FormData();
    formData.append('file', $file, $file.name);
    var xhr = new XMLHttpRequest();
    xhr.open('POST', uploadApi, true);
    xhr.onreadystatechange = function () {
      if (xhr.readyState === 4) {
        var response = JSON.parse(xhr.responseText);
        if (response.state.toLowerCase() == 'success') {
          uploadSuccessIndex++;
          fileUrls.push(response.url);
          if (uploadSuccessIndex == file.length) {
            self.loading_remark = false;
            callback(fileUrls);
          }
        } else {
          message.error('文件上传失败，请重试');
          uploadSuccessIndex++;
          if (uploadSuccessIndex == file.length) {
            callback(fileUrls);
          }
        }
      }
    };
    xhr.send(formData);
  }
}

function loadjs(url, callback, opts) {
  var script, i, d, len;
  if (!!url) {
    script = document.createElement("script");
    script.type = "text/javascript";
    if (!_.isEmpty(utils.isObjectAttribute(opts, ["data"]))) {
      for (i = 0, len = opts.data.length; i < len; i++) {
        d = opts.data[i];
        script.setAttribute(d.name, d.value);
      }
    }
    if (typeof(callback) != "undefined") {
      if (script.readyState) {
        script.onreadystatechange = function () {
          if (script.readyState == "loaded" || script.readyState == "complete") {
            script.onreadystatechange = null;
            callback();
          }
        };
      } else {
        script.onload = function () {
          callback();
        };
        script.onerror = function () {
          callback();
        };
      }
    }
    script.src = url;
    document.getElementsByTagName('head')[0].appendChild(script);
  } else {
    callback();
  }
}

function loadcss(url, callback) {
  var css = document.createElement("link");
  css.rel = "stylesheet";
  if (typeof(callback) != "undefined") {
    if (css.readyState) {
      css.onreadystatechange = function () {
        if (css.readyState == "loaded" || css.readyState == "complete") {
          css.onreadystatechange = null;
          callback();
        }
      };
    } else {
      css.onload = function () {
        callback();
      };
      css.onerror = function () {
        callback();
      }
    }
  }
  css.href = url;
  document.getElementsByTagName('head')[0].appendChild(css);
}

function getStorageService(callbackFn) {
  if (!config.storageService) {
    ajax('BizConfig/search', {
      "terms": [{"code": "code", "type": "text", "value": "storageService"}],
      "index": 0,
      "size": 30
    }).then(res => {
      config.storageService = res.data.content[0].value;
      utils.setCookie(config.cookieName.storageService, config.storageService);
      callbackFn(config.storageService);
    });
  } else {
    callbackFn(config.storageService);
  }
}


function setZoom(el, uiData) {
  console.log("uiData.direction:::::::::"+JSON.stringify(uiData))
  var windowHeight = el.offsetHeight;
  var windowWidth = el.offsetWidth;
  var width = el.parentNode.offsetWidth;
  var height = el.parentNode.offsetHeight;
  (function () {
      if (windowWidth > windowHeight) {
        el.style.zoom = width / 1920;
        let size = width / 1920 ;
        el.style.WebkitTransform = ' scale('+size+','+size+')';
        el.style.MsTransform = ' scale('+size+','+size+')';
        el.style.MozTransform = ' scale('+size+','+size+')';
        el.style.OTransform = ' scale('+size+','+size+')';
        el.style.transform  = ' scale('+size+')';
        el.style.transformOrigin  = '0 0';
      } else {
        // if (width >= 1080) {
        //   if (height < 1920) {
        //     console.log("11111111")
        //     el.style.zoom = height / 1920;
        //     el.style.margin = '0 auto';
        //   } else {
        //     el.style.zoom = 1;
        //   }
        // } else {
        //   console.log("22222")
        //   el.style.zoom = width / 1080;
        // }

        if(width>height){
          console.log("444444444444s");
          let size = width / 1920 ;
          // el.style.zoom = width / 1920 ;
          // el.style.WebkitTransform = ' scale('+size+','+size+')';
          // el.style.MsTransform = ' scale('+size+','+size+')';
          // el.style.MozTransform = ' scale('+size+','+size+')';
          // el.style.OTransform = ' scale('+size+','+size+')';
          el.style.transform  = ' scale('+size+')';
          el.style.transformOrigin  = '0 0';
        }else {
          console.log("3333333333");
          // el.style.zoom = width / 1080;
          let size = width / 1080 ;
          // el.style.WebkitTransform = ' scale('+size+','+size+')';
          // el.style.MsTransform = ' scale('+size+','+size+')';
          // el.style.MozTransform = ' scale('+size+','+size+')';
          // el.style.OTransform = ' scale('+size+','+size+')';
          el.style.transform  = ' scale('+size+')';
          el.style.transformOrigin  = '0 0';
        }
      }
  })();

  //setTimeout(function () {
  //  printData(uiData);
  //}, 1000)
}

export default {
  message: message,
  utils: utils,
  config: config,
  goRouter: goRouter,
  goLogin: goLogin,
  routerBack: routerBack,
  ajax: ajax,
  parseEditorJSON: parseEditorJSON,
  url: url,
  compare: compare,
  user: user,
  passCheck: passCheck,
  genQueryTerms: genQueryTerms,
  parseQueryTerms: parseQueryTerms,
  _: _,
  setTitle: setTitle,
  upload: upload,
  loadjs: loadjs,
  loadcss: loadcss,
  loading: loading,
  closeLoading: closeLoading,
  getStorageService: getStorageService,
  setZoom: setZoom
};


// WEBPACK FOOTER //
// ./src/core/framework.js
